import { Init, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsPromoMtEntity } from '../entity/promo_mt';

/**
 * 促销汇总服务
 */
@Provide()
export class GoodsPromoMtService extends BaseService {
  @InjectEntityModel(GoodsPromoMtEntity)
  promoMtEntity: Repository<GoodsPromoMtEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.promoMtEntity);
  }

  /**
   * 根据促销类型获取促销列表
   * @param promType 促销类型
   * @param status 状态
   */
  async getByPromType(promType?: string, status: number = 1) {
    const where: any = { status };
    if (promType) {
      where.promType = promType;
    }
    return await this.promoMtEntity.find({
      where,
      order: { createTime: 'DESC' }
    });
  }

  /**
   * 获取有效的促销活动
   */
  async getActivePromos() {
    const now = new Date();
    return await this.promoMtEntity
      .createQueryBuilder('promo')
      .where('promo.status = :status', { status: 1 })
      .andWhere('promo.startTime <= :now', { now })
      .andWhere('promo.endTime >= :now', { now })
      .orderBy('promo.createTime', 'DESC')
      .getMany();
  }

  /**
   * 根据单据号获取促销信息
   * @param billNo 单据号
   */
  async getByBillNo(billNo: string) {
    return await this.promoMtEntity.findOne({
      where: { billNo }
    });
  }

  /**
   * 根据促销类型获取促销详情列表（关联商品信息和明细）
   * @param promType 促销类型 (TC/MJ/MS/MZ)
   */
  async getComboDetailsByType(promType?: string) {
    let whereClause = 'mt.status = 1';
    let params = [];
    
    if (promType) {
      switch (promType) {
        case 'TC':
          whereClause += ' AND mt.promType = ?';
          params.push('套餐');
          break;
        case 'MJ':
          whereClause += ' AND mt.promType = ?';
          params.push('满减');
          break;
        case 'MS':
          whereClause += ' AND mt.promType = ?';
          params.push('秒杀');
          break;
        case 'MZ':
          whereClause += ' AND mt.promType = ?';
          params.push('买赠');
          break;
      }
    }

    // 获取促销汇总信息
    const mtQuery = `
      SELECT 
        mt.billNo,
        mt.billCode,
        mt.promName,
        mt.promType,
        mt.startTime,
        mt.endTime,
        mt.status
      FROM goods_promo_mt mt
      WHERE ${whereClause}
      ORDER BY mt.createTime DESC
    `;

    const promoList = await this.promoMtEntity.query(mtQuery, params);
    
    // 为每个促销活动获取对应的明细数据
    const results = [];
    for (const promo of promoList) {
      const promoData = {
        billNo: promo.billNo,
        billCode: promo.billCode,
        promName: promo.promName,
        promType: promo.promType,
        startTime: promo.startTime,
        endTime: promo.endTime,
        status: promo.status,
        details: []
      };

      // 根据促销类型获取对应的明细数据
      switch (promType) {
        case 'TC': // 套餐
          const tcDetails = await this.getPromoTcDetails(promo.billNo);
          promoData.details = tcDetails;
          break;
        case 'MJ': // 满减
          const mjDetails = await this.getPromoMjDetails(promo.billNo);
          promoData.details = mjDetails;
          break;
        case 'MS': // 秒杀
          const msDetails = await this.getPromoMsDetails(promo.billNo);
          promoData.details = msDetails;
          break;
        case 'MZ': // 买赠
          const mzDetails = await this.getPromoMzDetails(promo.billNo);
          promoData.details = mzDetails;
          break;
      }

      results.push(promoData);
    }
    
    return results;
  }

  /**
   * 根据商品ID获取该商品参与的所有促销活动
   * @param goodsId 商品ID
   */
  async getCombosByGoodsId(goodsId: string) {
    // 查找该商品参与的所有促销活动
    const promoQuery = `
      SELECT DISTINCT mt.billNo, mt.billCode, mt.promName, mt.promType, mt.startTime, mt.endTime, mt.status
      FROM goods_promo_mt mt
      WHERE mt.status = 1 AND mt.billNo IN (
        SELECT DISTINCT billNo FROM goods_promo_tc WHERE goodsId = ? AND status = 1
        UNION
        SELECT DISTINCT billNo FROM goods_promo_mz WHERE goodsId = ? AND status = 1
        UNION
        SELECT DISTINCT billNo FROM goods_promo_ms WHERE goodsId = ? AND status = 1
      )
      ORDER BY mt.createTime DESC
    `;

    const promoList = await this.promoMtEntity.query(promoQuery, [goodsId, goodsId, goodsId]);
    
    // 为每个促销活动获取完整的明细数据
    const results = [];
    for (const promo of promoList) {
      const promoData = {
        billNo: promo.billNo,
        billCode: promo.billCode,
        promName: promo.promName,
        promType: promo.promType,
        startTime: promo.startTime,
        endTime: promo.endTime,
        status: promo.status,
        details: [],
        totalPrice: 0
      };

      // 根据促销类型获取对应的明细数据
      switch (promo.promType) {
        case 'TC': // 套餐
          const tcDetails = await this.getPromoTcDetails(promo.billNo);
          promoData.details = tcDetails;
          promoData.totalPrice = tcDetails.reduce((sum, detail) => sum + (detail.taxprice * detail.num), 0);
          break;
        case 'MJ': // 满减
          const mjDetails = await this.getPromoMjDetails(promo.billNo);
          promoData.details = mjDetails;
          break;
        case 'MS': // 秒杀
          const msDetails = await this.getPromoMsDetails(promo.billNo);
          promoData.details = msDetails;
          break;
        case 'MZ': // 买赠
          const mzDetails = await this.getPromoMzDetails(promo.billNo);
          promoData.details = mzDetails;
          break;
      }

      results.push(promoData);
    }
    
    return results;
  }

  /**
   * 获取套餐明细（TC类型）
   * @param billNo 单据号
   */
  private async getPromoTcDetails(billNo: string) {
    const query = `
      SELECT 
        tc.id,
        tc.billSn,
        tc.goodsId,
        tc.num,
        tc.taxprice,
        tc.status,
        gi.*
      FROM goods_promo_tc tc
      LEFT JOIN goods_info gi ON tc.goodsId = gi.goodsId
      WHERE tc.billNo = ? AND tc.status = 1
      ORDER BY tc.billSn ASC
    `;

    const results = await this.promoMtEntity.query(query, [billNo]);
    return results.map(detail => ({
      id: detail.id,
      billSn: detail.billSn,
      goodsId: detail.goodsId,
      num: detail.num,
      taxprice: detail.taxprice,
      status: detail.status,
      goodsInfo: {
        id: detail.id_1, // gi.id 会被重命名为 id_1
        typeId: detail.typeId,
        title: detail.title,
        subTitle: detail.subTitle,
        mainPic: detail.mainPic,
        pics: detail.pics ? JSON.parse(detail.pics) : [],
        price: detail.price,
        sold: detail.sold,
        content: detail.content,
        status: detail.status_1, // gi.status 会被重命名为 status_1
        sortNum: detail.sortNum,
        attribute: detail.attribute,
        goodsId: detail.goodsId_1, // gi.goodsId 会被重命名为 goodsId_1
        entId: detail.entId,
        goodsCode: detail.goodsCode,
        oracleGoodsName: detail.oracleGoodsName,
        goodsSpec: detail.goodsSpec,
        manufacturer: detail.manufacturer,
        unit: detail.unit,
        approvalNo: detail.approvalNo,
        formula: detail.formula,
        midpack: detail.midpack,
        qty: detail.qty,
        planCate: detail.planCate,
        logogram: detail.logogram,
        wholLimtNum: detail.wholLimtNum,
        storNum: detail.storNum,
        isMidpackSaleDisabled: detail.isMidpackSaleDisabled,
        gCategory: detail.gCategory,
        qCategory: detail.qCategory,
        oracleIsHidden: detail.oracleIsHidden,
        isPres: detail.isPres,
        saleTaxPriceL1: detail.saleTaxPriceL1,
        salePriceL1: detail.salePriceL1,
        saleTaxPriceL2: detail.saleTaxPriceL2,
        salePriceL2: detail.salePriceL2,
        saleTaxPriceL3: detail.saleTaxPriceL3,
        salePriceL3: detail.salePriceL3,
        saleTaxPriceL4: detail.saleTaxPriceL4,
        salePriceL4: detail.salePriceL4,
        brandCode: detail.brandCode,
        nextValPrice: detail.nextValPrice,
        createTime: detail.createTime_1, // gi.createTime 会被重命名为 createTime_1
        updateTime: detail.updateTime_1 // gi.updateTime 会被重命名为 updateTime_1
      }
    }));
  }

  /**
   * 获取满减明细（MJ类型）
   * @param billNo 单据号
   */
  private async getPromoMjDetails(billNo: string) {
    const query = `
      SELECT 
        mj.id,
        mj.billSn,
        mj.taxAmount,
        mj.dedRate,
        mj.status
      FROM goods_promo_mj mj
      WHERE mj.billNo = ? AND mj.status = 1
      ORDER BY mj.billSn ASC
    `;

    const results = await this.promoMtEntity.query(query, [billNo]);
    return results.map(detail => ({
      id: detail.id,
      billSn: detail.billSn,
      taxAmount: detail.taxAmount,
      dedRate: detail.dedRate,
      status: detail.status,
      description: `满${Number(detail.taxAmount).toFixed(2)}元${Number(detail.dedRate).toFixed(0)}折`
    }));
  }

  /**
   * 获取秒杀明细（MS类型）
   * @param billNo 单据号
   */
  private async getPromoMsDetails(billNo: string) {
    const query = `
      SELECT 
        ms.id,
        ms.billSn,
        ms.goodsId,
        ms.seckillNum,
        ms.seckillPrice,
        ms.seckillStorNum,
        ms.status,
        gi.*
      FROM goods_promo_ms ms
      LEFT JOIN goods_info gi ON ms.goodsId = gi.goodsId
      WHERE ms.billNo = ? AND ms.status = 1
      ORDER BY ms.billSn ASC
    `;

    const results = await this.promoMtEntity.query(query, [billNo]);
    return results.map(detail => ({
      id: detail.id,
      billSn: detail.billSn,
      goodsId: detail.goodsId,
      seckillNum: detail.seckillNum,
      seckillPrice: detail.seckillPrice,
      seckillStorNum: detail.seckillStorNum,
      status: detail.status,
      goodsInfo: {
        id: detail.id_1,
        typeId: detail.typeId,
        title: detail.title,
        subTitle: detail.subTitle,
        mainPic: detail.mainPic,
        pics: detail.pics ? JSON.parse(detail.pics) : [],
        price: detail.price,
        sold: detail.sold,
        content: detail.content,
        status: detail.status_1,
        sortNum: detail.sortNum,
        attribute: detail.attribute,
        goodsId: detail.goodsId_1,
        entId: detail.entId,
        goodsCode: detail.goodsCode,
        oracleGoodsName: detail.oracleGoodsName,
        goodsSpec: detail.goodsSpec,
        manufacturer: detail.manufacturer,
        unit: detail.unit,
        approvalNo: detail.approvalNo,
        formula: detail.formula,
        midpack: detail.midpack,
        qty: detail.qty,
        planCate: detail.planCate,
        logogram: detail.logogram,
        wholLimtNum: detail.wholLimtNum,
        storNum: detail.storNum,
        isMidpackSaleDisabled: detail.isMidpackSaleDisabled,
        gCategory: detail.gCategory,
        qCategory: detail.qCategory,
        oracleIsHidden: detail.oracleIsHidden,
        isPres: detail.isPres,
        saleTaxPriceL1: detail.saleTaxPriceL1,
        salePriceL1: detail.salePriceL1,
        saleTaxPriceL2: detail.saleTaxPriceL2,
        salePriceL2: detail.salePriceL2,
        saleTaxPriceL3: detail.saleTaxPriceL3,
        salePriceL3: detail.salePriceL3,
        saleTaxPriceL4: detail.saleTaxPriceL4,
        salePriceL4: detail.salePriceL4,
        brandCode: detail.brandCode,
        nextValPrice: detail.nextValPrice,
        createTime: detail.createTime_1,
        updateTime: detail.updateTime_1
      }
    }));
  }

  /**
   * 获取买赠明细（MZ类型）
   * @param billNo 单据号
   */
  private async getPromoMzDetails(billNo: string) {
    const query = `
      SELECT 
        mz.id,
        mz.billSn,
        mz.goodsId,
        mz.num,
        mz.freeId,
        mz.freeNum,
        mz.freeTaxPrice,
        mz.taxprice,
        mz.status,
        gi.*,
        fgi.id as fgi_id,
        fgi.typeId as fgi_typeId,
        fgi.title as fgi_title,
        fgi.subTitle as fgi_subTitle,
        fgi.mainPic as fgi_mainPic,
        fgi.pics as fgi_pics,
        fgi.price as fgi_price,
        fgi.sold as fgi_sold,
        fgi.content as fgi_content,
        fgi.status as fgi_status,
        fgi.sortNum as fgi_sortNum,
        fgi.attribute as fgi_attribute,
        fgi.goodsId as fgi_goodsId,
        fgi.entId as fgi_entId,
        fgi.goodsCode as fgi_goodsCode,
        fgi.oracleGoodsName as fgi_oracleGoodsName,
        fgi.goodsSpec as fgi_goodsSpec,
        fgi.manufacturer as fgi_manufacturer,
        fgi.unit as fgi_unit,
        fgi.approvalNo as fgi_approvalNo,
        fgi.formula as fgi_formula,
        fgi.midpack as fgi_midpack,
        fgi.qty as fgi_qty,
        fgi.planCate as fgi_planCate,
        fgi.logogram as fgi_logogram,
        fgi.wholLimtNum as fgi_wholLimtNum,
        fgi.storNum as fgi_storNum,
        fgi.isMidpackSaleDisabled as fgi_isMidpackSaleDisabled,
        fgi.gCategory as fgi_gCategory,
        fgi.qCategory as fgi_qCategory,
        fgi.oracleIsHidden as fgi_oracleIsHidden,
        fgi.isPres as fgi_isPres,
        fgi.saleTaxPriceL1 as fgi_saleTaxPriceL1,
        fgi.salePriceL1 as fgi_salePriceL1,
        fgi.saleTaxPriceL2 as fgi_saleTaxPriceL2,
        fgi.salePriceL2 as fgi_salePriceL2,
        fgi.saleTaxPriceL3 as fgi_saleTaxPriceL3,
        fgi.salePriceL3 as fgi_salePriceL3,
        fgi.saleTaxPriceL4 as fgi_saleTaxPriceL4,
        fgi.salePriceL4 as fgi_salePriceL4,
        fgi.brandCode as fgi_brandCode,
        fgi.nextValPrice as fgi_nextValPrice,
        fgi.createTime as fgi_createTime,
        fgi.updateTime as fgi_updateTime
      FROM goods_promo_mz mz
      LEFT JOIN goods_info gi ON mz.goodsId = gi.goodsId
      LEFT JOIN goods_info fgi ON mz.freeId = fgi.goodsId
      WHERE mz.billNo = ? AND mz.status = 1
      ORDER BY mz.billSn ASC
    `;

    const results = await this.promoMtEntity.query(query, [billNo]);
    return results.map(detail => ({
      id: detail.id,
      billSn: detail.billSn,
      goodsId: detail.goodsId,
      num: detail.num,
      freeId: detail.freeId,
      freeNum: detail.freeNum,
      freeTaxPrice: detail.freeTaxPrice,
      taxprice: detail.taxprice,
      status: detail.status,
      goodsInfo: {
        id: detail.id_1,
        typeId: detail.typeId,
        title: detail.title,
        subTitle: detail.subTitle,
        mainPic: detail.mainPic,
        pics: detail.pics ? JSON.parse(detail.pics) : [],
        price: detail.price,
        sold: detail.sold,
        content: detail.content,
        status: detail.status_1,
        sortNum: detail.sortNum,
        attribute: detail.attribute,
        goodsId: detail.goodsId_1,
        entId: detail.entId,
        goodsCode: detail.goodsCode,
        oracleGoodsName: detail.oracleGoodsName,
        goodsSpec: detail.goodsSpec,
        manufacturer: detail.manufacturer,
        unit: detail.unit,
        approvalNo: detail.approvalNo,
        formula: detail.formula,
        midpack: detail.midpack,
        qty: detail.qty,
        planCate: detail.planCate,
        logogram: detail.logogram,
        wholLimtNum: detail.wholLimtNum,
        storNum: detail.storNum,
        isMidpackSaleDisabled: detail.isMidpackSaleDisabled,
        gCategory: detail.gCategory,
        qCategory: detail.qCategory,
        oracleIsHidden: detail.oracleIsHidden,
        isPres: detail.isPres,
        saleTaxPriceL1: detail.saleTaxPriceL1,
        salePriceL1: detail.salePriceL1,
        saleTaxPriceL2: detail.saleTaxPriceL2,
        salePriceL2: detail.salePriceL2,
        saleTaxPriceL3: detail.saleTaxPriceL3,
        salePriceL3: detail.salePriceL3,
        saleTaxPriceL4: detail.saleTaxPriceL4,
        salePriceL4: detail.salePriceL4,
        brandCode: detail.brandCode,
        nextValPrice: detail.nextValPrice,
        createTime: detail.createTime_1,
        updateTime: detail.updateTime_1
      },
      freeGoodsInfo: {
        id: detail.fgi_id,
        typeId: detail.fgi_typeId,
        title: detail.fgi_title,
        subTitle: detail.fgi_subTitle,
        mainPic: detail.fgi_mainPic,
        pics: detail.fgi_pics ? JSON.parse(detail.fgi_pics) : [],
        price: detail.fgi_price,
        sold: detail.fgi_sold,
        content: detail.fgi_content,
        status: detail.fgi_status,
        sortNum: detail.fgi_sortNum,
        attribute: detail.fgi_attribute,
        goodsId: detail.fgi_goodsId,
        entId: detail.fgi_entId,
        goodsCode: detail.fgi_goodsCode,
        oracleGoodsName: detail.fgi_oracleGoodsName,
        goodsSpec: detail.fgi_goodsSpec,
        manufacturer: detail.fgi_manufacturer,
        unit: detail.fgi_unit,
        approvalNo: detail.fgi_approvalNo,
        formula: detail.fgi_formula,
        midpack: detail.fgi_midpack,
        qty: detail.fgi_qty,
        planCate: detail.fgi_planCate,
        logogram: detail.fgi_logogram,
        wholLimtNum: detail.fgi_wholLimtNum,
        storNum: detail.fgi_storNum,
        isMidpackSaleDisabled: detail.fgi_isMidpackSaleDisabled,
        gCategory: detail.fgi_gCategory,
        qCategory: detail.fgi_qCategory,
        oracleIsHidden: detail.fgi_oracleIsHidden,
        isPres: detail.fgi_isPres,
        saleTaxPriceL1: detail.fgi_saleTaxPriceL1,
        salePriceL1: detail.fgi_salePriceL1,
        saleTaxPriceL2: detail.fgi_saleTaxPriceL2,
        salePriceL2: detail.fgi_salePriceL2,
        saleTaxPriceL3: detail.fgi_saleTaxPriceL3,
        salePriceL3: detail.fgi_salePriceL3,
        saleTaxPriceL4: detail.fgi_saleTaxPriceL4,
        salePriceL4: detail.fgi_salePriceL4,
        brandCode: detail.fgi_brandCode,
        nextValPrice: detail.fgi_nextValPrice,
        createTime: detail.fgi_createTime,
        updateTime: detail.fgi_updateTime
      }
    }));
  }
} 